package com.atnjupt.admin.interceptor;

import com.atnjupt.admin.bean.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 拦截器三步骤
 * 1、创建一个拦截器实现HandlerInterceptor
 * 2、拦截器注册到容器中（实现WebMvcConfigurer的addInterceptors）
 * 3、指定拦截规则【如果是拦截所有，静态资源也会被拦截】
 * @author Wizarder
 * @create 2021-10-13 11:55
 */
@Slf4j
public class AdminInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.info("请求前preHandle拦截路径" + requestURI);
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        //如果用户已经登录就放行
        if (user != null){
            return true;
        }
        //否则拦截
        request.setAttribute("msg","请用户先登录");
        //请求转发到登录页面
        request.getRequestDispatcher("/login").forward(request,response);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("请求后的postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("视图渲染后afterCompletion");
    }
}
